package com.example.view;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.example.config.GlobalConfig;
import com.example.entry.BodyEntry;
import com.example.entry.BodyVo;
import com.example.entry.HeaderEntry;
import com.example.entry.HeaderVo;
import com.example.entry.RequestHistory;
import com.example.log.Logs;
import com.example.utils.HistoryUtils;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;

public class WebHttpView {

	@FXML
	private ListView<RequestHistory> historyListView;
	@FXML
	private ComboBox<String> methodComboBox;
	@FXML
	private TextField urlField;
	@FXML
	private Button sendButton;
	@FXML
	private TabPane requestTabPane;
	@FXML
	private VBox bodyContainer;
	@FXML
	private RadioButton formDataRadio;
	@FXML
	private RadioButton rawRadio;
	@FXML
	private Button addHeaderButton;
	@FXML
	private Button addCookieButton;
	@FXML
	private Button addFormDataButton;
	@FXML
	private TextArea rawTextArea;
	@FXML
	private ComboBox<String> rawTypeComboBox;
	@FXML
	private TextField nameField;
	@FXML
	private Button saveButton;
	@FXML
	private Button resetButton;
	@FXML
	private TabPane responseTabPane;
	@FXML
	private TextArea responseBodyArea;
	@FXML
	private TableView<HeaderEntry> responseHeadersTable;
	@FXML
	private TableView<HeaderEntry> responseCookiesTable;
	@FXML
	private Label responseStatusLabel;
	@FXML
	private Button switchToWsButton;
	@FXML
	private Button globalConfigButton;
	@FXML
	private VBox headersContainer;
	@FXML
	private VBox cookiesContainer;
	@FXML
	private VBox formDataEntriesContainer;
	@FXML
	private TextField headerNameField;
	@FXML
	private TextField headerValueField;
	@FXML
	private TextField cookieNameField;
	@FXML
	private TextField cookieValueField;
	private TextField formDataNameField;
	private TextField formDataValueField;
	private ComboBox<String> formDataTypeComboBox;
	private List<HeaderEntry> headers = new ArrayList<>();
	private List<HeaderEntry> cookies = new ArrayList<>();
	private List<BodyEntry> formDataEntries = new ArrayList<>();

	private int index = 1;
	private List<RequestHistory> historyList = new ArrayList<>();
	private File lastDirectory;
	private String currentUuid;

	public void initialize() {
		// 生成初始UUID
		currentUuid = java.util.UUID.randomUUID().toString();

		// 初始化请求方法下拉框
		methodComboBox.setItems(FXCollections.observableArrayList(
				"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "TRACE", "CONNECT"
		));
		methodComboBox.setValue("GET");

		// 初始化RAW类型下拉框
		rawTypeComboBox.setItems(FXCollections.observableArrayList(
				"JSON", "XML", "HTML"
		));
		rawTypeComboBox.setValue("JSON");

		// 设置单选按钮组
		ToggleGroup bodyTypeGroup = new ToggleGroup();
		formDataRadio.setToggleGroup(bodyTypeGroup);
		rawRadio.setToggleGroup(bodyTypeGroup);
		formDataRadio.setSelected(true);

		// 根据选择显示不同的请求体输入方式
		formDataRadio.selectedProperty().addListener((obs, oldVal, newVal) -> {
			formDataEntriesContainer.setVisible(newVal);
			formDataEntriesContainer.setManaged(newVal);
			rawTextArea.setVisible(!newVal);
			rawTextArea.setManaged(!newVal);
			rawTypeComboBox.setVisible(!newVal);
			rawTypeComboBox.setManaged(!newVal);
		});


		VBox headerBox = new VBox(5);

		headerBox.getChildren().addAll(
				createInputRow(
						headerNameField = new TextField(),
						headerValueField = new TextField(),
						new Button(""),  // 空按钮占位
						this::addHeader
				)
		);
		headersContainer.getChildren().add(headerBox);

		// Cookies 区域
		VBox cookieBox = new VBox(5);

		cookieBox.getChildren().addAll(
				createInputRow(
						cookieNameField = new TextField(),
						cookieValueField = new TextField(),
						new Button(""),  // 空按钮占位
						this::addCookie
				)
		);
		cookiesContainer.getChildren().add(cookieBox);

		VBox formDataBox = new VBox(5);

		formDataBox.getChildren().addAll(
				createFormDataInputRow(
						formDataNameField = new TextField(),
						formDataValueField = new TextField(),
						formDataTypeComboBox = new ComboBox<>(),
						this::addFormData
				)
		);
		formDataEntriesContainer.getChildren().add(formDataBox);

		// 添加按钮事件
		addHeaderButton.setOnAction(e -> addHeader());
		addCookieButton.setOnAction(e -> addCookie());
		addFormDataButton.setOnAction(e -> addFormData());

		// 初始化响应区域表格
		initResponseHeadersTable();
		initResponseCookiesTable();

		// 添加按钮事件处理
		if (sendButton != null) {
			sendButton.setOnAction(e -> sendRequest());
		}
		if (saveButton != null) {
			saveButton.setOnAction(e -> saveToHistory());
		}
		if (resetButton != null) {
			resetButton.setOnAction(e -> resetForm());
		}
		if (globalConfigButton != null) {
			globalConfigButton.setOnAction(e -> showGlobalConfig());
		}
		if (switchToWsButton != null) {
			switchToWsButton.setOnAction(e -> {
				try {
					FXMLLoader loader = new FXMLLoader(getClass().getResource("WebSocketView.fxml"));
					Parent root = loader.load();
					Scene scene = new Scene(root);
					Stage stage = (Stage) switchToWsButton.getScene().getWindow();
					stage.setScene(scene);
				} catch (IOException ex) {
					showAlert("错误", "加载WebSocket界面失败: " + ex.getMessage(), Alert.AlertType.ERROR);
				}
			});
		}

		// 加载历史记录
		historyList = HistoryUtils.loadHistoryFromFile();
		updateHistoryListView();

		// 显示全局配置
		displayGlobalConfig();
	}

	private HBox createInputRow(TextField nameField, TextField valueField, Button addButton, Runnable addAction) {
		HBox row = new HBox(5);
		row.setAlignment(Pos.CENTER_LEFT);
		row.setPadding(new Insets(2));
		row.setStyle("-fx-background-color: #f6f8fa; -fx-background-radius: 6;");

		nameField.setPromptText("参数名");
		nameField.setPrefWidth(200);
		nameField.setPrefHeight(30);
		nameField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		valueField.setPromptText("参数值");
		valueField.setPrefHeight(30);
		HBox.setHgrow(valueField, Priority.ALWAYS);
		valueField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		// 修改为在参数值失去焦点且有内容时添加
		valueField.focusedProperty().addListener((obs, oldVal, newVal) -> {
			if (!newVal) {  // 失去焦点时
				String name = nameField.getText().trim();
				String value = valueField.getText().trim();
				if (!name.isEmpty() && !value.isEmpty()) {
					Node nextFocus = nameField.getScene().getFocusOwner();
					Platform.runLater(() -> {
						addAction.run();
						if (nextFocus != null) {
							nextFocus.requestFocus();
						}
					});
				}
			}
		});

		addButton.setOnAction(e -> {
			String name = nameField.getText().trim();
			String value = valueField.getText().trim();
			if (!name.isEmpty() && !value.isEmpty()) {
				addAction.run();
			}
		});

		row.getChildren().addAll(nameField, valueField, addButton);
		return row;
	}

	private HBox createFormDataInputRow(TextField nameField, TextField valueField,
	                                    ComboBox<String> typeComboBox, Runnable addAction) {
		HBox row = new HBox(5);
		row.setAlignment(Pos.CENTER_LEFT);
		row.setPadding(new Insets(2));
		row.setStyle("-fx-background-color: #f6f8fa; -fx-background-radius: 6;");

		nameField.setPromptText("参数名");
		nameField.setPrefWidth(200);
		nameField.setPrefHeight(30);
		nameField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		typeComboBox.setPrefHeight(30);
		typeComboBox.setMinWidth(100);
		typeComboBox.setMaxWidth(100);
		typeComboBox.setItems(FXCollections.observableArrayList("字符串", "文件"));
		typeComboBox.setValue("字符串");
		typeComboBox.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		// 创建文件选择按钮和值输入框
		Button fileButton = new Button("选择文件");
		fileButton.getStyleClass().add("secondary-button");

		valueField.setPromptText("参数值");
		valueField.setPrefHeight(30);
		HBox.setHgrow(valueField, Priority.ALWAYS);
		valueField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		// 使用数组来存储当前的值控件，这样可以在 lambda 中修改
		final Node[] currentValueControl = {valueField};

		// 类型改变时的处理
		typeComboBox.valueProperty().addListener((obs, oldVal, newVal) -> {
			int valueIndex = row.getChildren().indexOf(currentValueControl[0]);
			if ("文件".equals(newVal)) {
				row.getChildren().set(valueIndex, fileButton);
				currentValueControl[0] = fileButton;
			} else {
				row.getChildren().set(valueIndex, valueField);
				currentValueControl[0] = valueField;
			}
		});

		fileButton.setOnAction(e -> {
			String name = nameField.getText().trim();
			if (!name.isEmpty()) {
				// 创建一个临时的 BodyEntry 来存储文件
				BodyEntry tempEntry = new BodyEntry();
				tempEntry.setName(name);
				tempEntry.setType("文件");

				File file = showFileChooser(tempEntry);
				if (file != null) {
					fileButton.setText(file.getName());
					// 使用临时创建的 entry 来添加新行
					Platform.runLater(() -> {
						// 将当前行的数据添加到列表中
						BodyEntry entry = new BodyEntry();
						entry.setName(name);
						entry.setType("文件");
						entry.setValue(file);
						entry.setFullPath(file.getAbsolutePath());
						formDataEntries.add(entry);

						// 创建新的行并添加到列表中
						HBox newRow = createFormDataRow(entry, formDataEntries, formDataEntriesContainer);
						formDataEntriesContainer.getChildren().add(
								formDataEntriesContainer.getChildren().size() - 1, newRow);

						// 清空当前输入行
						nameField.clear();
						// 重置当前行为字符串类型
						typeComboBox.setValue("字符串");
						// 确保当前行显示为文本输入框
						valueField.clear();
					});
				}
			}
		});

		// 修改为在参数值失去焦点且有内容时添加
		valueField.focusedProperty().addListener((obs, oldVal, newVal) -> {
			if (!newVal) {  // 失去焦点时
				String name = nameField.getText().trim();
				String value = valueField.getText().trim();
				if (!name.isEmpty() && !value.isEmpty()) {
					Node nextFocus = nameField.getScene().getFocusOwner();
					Platform.runLater(() -> {
						addAction.run();
						if (nextFocus != null) {
							nextFocus.requestFocus();
						}
					});
				}
			}
		});


		row.getChildren().addAll(nameField, typeComboBox, currentValueControl[0]);
		return row;
	}

	// 检查节点是否在表格编辑区域内
	private boolean isInTableEdit(Node node) {
		if (node == null) {
			return false;
		}

		// 如果点击的是文本框或其父节点是TableCell，则认为是在编辑区域内
		if (node instanceof TextField || node instanceof TableCell) {
			return true;
		}

		// 检查是否点击在表格内部
		Node parent = node.getParent();
		while (parent != null) {
			if (parent instanceof TableCell || parent instanceof TextField) {
				return true;
			}
			parent = parent.getParent();
		}

		return false;
	}

	private void showGlobalConfig() {
		GlobalConfigDialog dialog = new GlobalConfigDialog();
		dialog.setOnCloseRequest(event -> {
			// 保存当前非全局的请求头和Cookies
			List<HeaderEntry> nonGlobalHeaders = headers.stream()
					.filter(h -> !h.isGlobal())
					.toList();
			List<HeaderEntry> nonGlobalCookies = cookies.stream()
					.filter(c -> !c.isGlobal())
					.toList();

			// 清空当前配置
			headers.clear();
			cookies.clear();
			headersContainer.getChildren().clear();
			cookiesContainer.getChildren().clear();

			// 重新显示全局配置
			displayGlobalConfig();

			// 恢复非全局配置
			for (HeaderEntry header : nonGlobalHeaders) {
				headers.add(header);
				HBox row = createHeaderRow(header, headers, headersContainer);
				headersContainer.getChildren().add(row);
			}

			for (HeaderEntry cookie : nonGlobalCookies) {
				cookies.add(cookie);
				HBox row = createHeaderRow(cookie, cookies, cookiesContainer);
				cookiesContainer.getChildren().add(row);
			}

			// 确保有一个空白行
			if (headersContainer.getChildren().isEmpty()) {
				addEmptyHeaderRow();
			}
			if (cookiesContainer.getChildren().isEmpty()) {
				addEmptyCookieRow();
			}
		});

		dialog.showAndWait();
	}

	private void displayGlobalConfig() {
		// 添加全局请求头
		List<HeaderEntry> globalHeaders = GlobalConfig.getInstance().getGlobalHeaders().stream()
				.filter(header -> header.getName() != null && !header.getName().trim().isEmpty())
				.map(header -> {
					HeaderEntry newHeader = new HeaderEntry(header.getName(), header.getValue());
					newHeader.setGlobal(true);
					return newHeader;
				})
				.toList();

		for (HeaderEntry header : globalHeaders) {
			headers.add(header);
			HBox row = createHeaderRow(header, headers, headersContainer);
			headersContainer.getChildren().add(row);
		}

		// 添加全局Cookies
		List<HeaderEntry> globalCookies = GlobalConfig.getInstance().getGlobalCookies().stream()
				.filter(cookie -> cookie.getName() != null && !cookie.getName().trim().isEmpty())
				.map(cookie -> {
					HeaderEntry newCookie = new HeaderEntry(cookie.getName(), cookie.getValue());
					newCookie.setGlobal(true);
					return newCookie;
				})
				.toList();

		for (HeaderEntry cookie : globalCookies) {
			cookies.add(cookie);
			HBox row = createHeaderRow(cookie, cookies, cookiesContainer);
			cookiesContainer.getChildren().add(row);
		}

		// 确保有一个空白行
		if (headersContainer.getChildren().isEmpty()) {
			addEmptyHeaderRow();
		}
		if (cookiesContainer.getChildren().isEmpty()) {
			addEmptyCookieRow();
		}
	}

	private void addEmptyHeaderRow() {
		headerNameField = new TextField();
		headerValueField = new TextField();
		HBox headerInputRow = createInputRow(headerNameField, headerValueField, new Button("添加"), this::addHeader);
		headersContainer.getChildren().add(headerInputRow);
	}

	private void addEmptyCookieRow() {
		cookieNameField = new TextField();
		cookieValueField = new TextField();
		HBox cookieInputRow = createInputRow(cookieNameField, cookieValueField, new Button("添加"), this::addCookie);
		cookiesContainer.getChildren().add(cookieInputRow);
	}

	@FXML
	private void addFormData() {
		String name = formDataNameField.getText().trim();
		String value = formDataValueField.getText().trim();
		String type = formDataTypeComboBox.getValue();

		if (!name.isEmpty()) {
			BodyEntry entry = new BodyEntry();
			entry.setName(name);
			entry.setType(type);
			entry.setValue(null);  // 清空值
			entry.setFullPath(null);  // 清空文件路径

			if ("文件".equals(type)) {
				if (formDataValueField.isVisible()) {
					entry.setValue(value);
				} else {
					// 如果是文件选择按钮，获取文件
					Button fileButton = (Button) formDataEntriesContainer.getChildren()
							.get(formDataEntriesContainer.getChildren().size() - 1)
							.lookup("Button");
					if (fileButton != null && !"选择文件".equals(fileButton.getText())) {
						File file = new File(fileButton.getText());
						entry.setValue(file);
						entry.setFullPath(file.getAbsolutePath());
					}
				}
			} else {
				entry.setValue(value);
			}

			formDataEntries.add(entry);

			// 创建新的行并插入到输入行之前
			HBox row = createFormDataRow(entry, formDataEntries, formDataEntriesContainer);
			formDataEntriesContainer.getChildren().add(formDataEntriesContainer.getChildren().size() - 1, row);

			// 清空输入框并重置为字符串类型
			formDataNameField.clear();
			formDataValueField.clear();
			formDataTypeComboBox.setValue("字符串");

			// 确保新的空白行显示为文本输入框
			Node valueControl = formDataEntriesContainer.getChildren()
					.get(formDataEntriesContainer.getChildren().size() - 1)
					.lookup(".text-field");
			if (valueControl != null) {
				valueControl.setVisible(true);
				valueControl.setManaged(true);
			}
		}
	}

	private HBox createFormDataRow(BodyEntry entry, List<BodyEntry> list, VBox container) {
		HBox row = new HBox(5);
		row.setAlignment(Pos.CENTER_LEFT);
		row.setPadding(new Insets(2));
		row.setStyle("-fx-background-color: #f6f8fa; -fx-background-radius: 6;");

		TextField nameField = new TextField(entry.getName());
		nameField.setPrefWidth(200);
		nameField.setPrefHeight(30);
		nameField.textProperty().bindBidirectional(entry.nameProperty());
		nameField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		ComboBox<String> typeComboBox = new ComboBox<>();
		typeComboBox.setPrefHeight(30);
		typeComboBox.setMinWidth(100);
		typeComboBox.setMaxWidth(100);
		typeComboBox.setItems(FXCollections.observableArrayList("字符串", "文件"));
		typeComboBox.setValue(entry.getType());
		typeComboBox.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		// 使用数组来存储可变引用
		final Node[] valueControlRef = new Node[1];

		// 创建初始的值控件
		if ("文件".equals(entry.getType())) {
			Button fileButton = new Button("选择文件");
			if (entry.getValue() instanceof File file) {
				fileButton.setText(file.getName());
			}
			fileButton.getStyleClass().add("secondary-button");
			fileButton.setOnAction(e -> {
				File file = showFileChooser(entry);
				if (file != null) {
					fileButton.setText(file.getName());
				}
			});
			valueControlRef[0] = fileButton;
		} else {
			TextField valueField = new TextField();
			if (entry.getValue() != null && !(entry.getValue() instanceof File)) {
				valueField.setText(entry.getValue().toString());
			}
			valueField.textProperty().addListener((obs, oldVal, newVal) ->
					entry.setValue(newVal));
			HBox.setHgrow(valueField, Priority.ALWAYS);
			valueField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");
			valueControlRef[0] = valueField;
		}

		// 类型改变时的处理
		typeComboBox.valueProperty().addListener((obs, oldVal, newVal) -> {
			entry.setType(newVal);
			entry.setValue(null);  // 清空值
			entry.setFullPath(null);  // 清空文件路径

			int index = row.getChildren().indexOf(valueControlRef[0]);
			if ("文件".equals(newVal)) {
				Button fileButton = new Button("选择文件");  // 总是显示"选择文件"
				fileButton.getStyleClass().add("secondary-button");
				fileButton.setOnAction(e -> {
					File file = showFileChooser(entry);
					if (file != null) {
						fileButton.setText(file.getName());
					}
				});
				row.getChildren().set(index, fileButton);
				valueControlRef[0] = fileButton;
			} else {
				TextField valueField = new TextField();
				HBox.setHgrow(valueField, Priority.ALWAYS);
				valueField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");
				valueField.textProperty().addListener((o, old, newV) ->
						entry.setValue(newV));
				row.getChildren().set(index, valueField);
				valueControlRef[0] = valueField;
			}
		});

		// 创建删除按钮
		Button deleteButton = new Button("删除");
		deleteButton.getStyleClass().addAll("button", "danger-button"); // 添加基础button类
		deleteButton.setOnAction(e -> {
			list.remove(entry);
			container.getChildren().remove(row);
		});

		row.getChildren().addAll(nameField, typeComboBox, valueControlRef[0], deleteButton);
		return row;
	}

	private File showFileChooser(BodyEntry entry) {
		if (entry == null) {
			return null;
		}

		FileChooser fileChooser = new FileChooser();
		fileChooser.setTitle("选择文件");
		if (lastDirectory != null) {
			fileChooser.setInitialDirectory(lastDirectory);
		}

		File file = fileChooser.showOpenDialog(null);
		if (file != null) {
			lastDirectory = file.getParentFile();
			entry.setValue(file);
			entry.setFullPath(file.getAbsolutePath());
		}
		return file;
	}

	private void showAlert(String title, String content, Alert.AlertType alertType) {
		Platform.runLater(() -> {
			Alert alert = new Alert(alertType);
			alert.setTitle(title);
			alert.setHeaderText(null);  // 不显示头部文本
			alert.setContentText(content);
			alert.show();
		});
	}

	private void sendRequest() {
		Logs.getInstance().log("开始发送请求...");

		// 让焦点离开编辑区域
		sendButton.requestFocus();

		String url = urlField.getText().trim();
		if (url.isEmpty()) {
			Logs.getInstance().log("错误: URL为空");
			showAlert("错误", "请输入URL", Alert.AlertType.ERROR);
			return;
		}

		Logs.getInstance().log("请求URL: " + url);
		Logs.getInstance().log("请求方法: " + methodComboBox.getValue());

		try {
			// 检查URL格式
			if (!url.startsWith("http://") && !url.startsWith("https://")) {
				url = "http://" + url;
			}

			Method method = Method.valueOf(methodComboBox.getValue());

			HttpRequest httpRequest = HttpRequest.of(url).method(method);

			// 添加 Cookies
			if (!cookies.isEmpty()) {
				List<String> cookieStrings = cookies.stream()
						.map(cookie -> cookie.getName() + "=" + cookie.getValue())
						.toList();
				if (cookieStrings.size() > 1) {
					httpRequest.cookie(ArrayUtil.join(cookieStrings.toArray(), "; "));
				} else {
					httpRequest.cookie(cookieStrings.get(0));
				}
			}

			// 添加请求头
			boolean contentTypeSet = false;
			for (HeaderEntry header : headers) {
				if ("Content-Type".equalsIgnoreCase(header.getName())) {
					contentTypeSet = true;
				}
				httpRequest.header(header.getName(), header.getValue(), true);
			}

			// 处理请求体
			if (formDataRadio.isSelected()) {
				for (BodyEntry formData : formDataEntries) {
					if (formData.getName() != null && !formData.getName().trim().isEmpty()) {
						if ("文件".equals(formData.getType())) {
							if (formData.getValue() instanceof File file) {
								httpRequest.form(formData.getName(), file);
							}
						} else {
							httpRequest.form(formData.getName(), formData.getValue());
						}
					}
				}
			} else {
				String rawType = rawTypeComboBox.getValue();
				String raw = rawTextArea.getText();

				if (!contentTypeSet) {
					String contentType = switch (rawType) {
						case "JSON" -> "application/json";
						case "XML" -> "application/xml";
						case "HTML" -> "text/html";
						default -> "application/octet-stream";
					};
					httpRequest.header("Content-Type", contentType, true);
				}
				httpRequest.body(raw);
			}

			long startTime = System.currentTimeMillis();
			HttpResponse execute = httpRequest.execute();
			long duration = System.currentTimeMillis() - startTime;
			String body = execute.body();
			List<HttpCookie> responseCookies = execute.getCookies();
			int status = execute.getStatus();
			String contentEncoding = execute.charset();

			boolean executeGzip = execute.isGzip();

			Logs.getInstance().log("请求发送成功");
			Logs.getInstance().log("响应状态码: " + status);

			Platform.runLater(() -> {
				// 创建水平布局容器
				HBox statusBox = new HBox(10);
				statusBox.setAlignment(Pos.CENTER_LEFT);

				// 状态码标签
				Label statusCodeLabel = new Label(String.format("状态码: %d", status));
				statusCodeLabel.setStyle(String.format(
						"-fx-background-color: %s; " +
								"-fx-text-fill: white; " +
								"-fx-padding: 4 8; " +
								"-fx-background-radius: 4;",
						getStatusColorClass(status)
				));

				// 响应大小标签
				String sizeText;

				long contentLength = execute.contentLength();
				long responseLength = contentLength;
				if (contentLength < 0) {
					responseLength = body.getBytes().length;
				}

				if (responseLength > 1024 * 1024 * 1024) { // 大于1GB
					sizeText = String.format("响应大小: %.2f GB", NumberUtil.div(responseLength, 1024 * 1024 * 1024));
				} else if (responseLength > 1024 * 1024) { // 大于1MB
					sizeText = String.format("响应大小: %.2f MB", NumberUtil.div(responseLength, 1024 * 1024));
				} else if (responseLength > 1024) { // 大于1KB
					sizeText = String.format("响应大小: %.2f KB", NumberUtil.div(responseLength, 1024));
				} else { // 处理contentLength为负数的情况
					sizeText = "响应大小: " + responseLength + " Byte";
				}

				// 根据大小设置不同的颜色
				String sizeColor;
				if (responseLength > 1024 * 1024 * 10) { // 大于10MB
					sizeColor = "#cf222e"; // 红色
				} else if (responseLength > 1024 * 1024) { // 大于1MB
					sizeColor = "#9a6700"; // 黄色
				} else if (responseLength > 1024) { // 大于1KB
					sizeColor = "#0969da"; // 蓝色
				} else if (responseLength >= 0) { // 大于等于0字节
					sizeColor = "#2ea043"; // 绿色
				} else {
					sizeColor = "#57606a"; // 灰色
				}

				Label sizeLabel = new Label(sizeText);
				sizeLabel.setStyle(
						"-fx-text-fill: white; " +
								String.format("-fx-background-color: %s; ", sizeColor) +
								"-fx-padding: 4 8; " +
								"-fx-background-radius: 4;"
				);

				// 响应时间标签
				Label durationLabel = new Label(String.format("响应时间: %d ms", duration));
				durationLabel.setStyle(String.format(
						"-fx-text-fill: white; " +
								"-fx-background-color: %s; " +
								"-fx-padding: 4 8; " +
								"-fx-background-radius: 4;",
						getDurationColorClass(duration)
				));

				// 添加基本信息
				statusBox.getChildren().addAll(statusCodeLabel, sizeLabel, durationLabel);

				// 如果有编码信息，添加编码标签
				if (contentEncoding != null && !contentEncoding.isEmpty()) {
					Label encodingLabel = new Label(String.format("编码: %s", contentEncoding));
					encodingLabel.setStyle(
							"-fx-text-fill: #24292f; " +
									"-fx-background-color: #f6f8fa; " +
									"-fx-padding: 4 8; " +
									"-fx-background-radius: 4; " +
									"-fx-border-color: #e1e4e8; " +
									"-fx-border-radius: 4;"
					);
					statusBox.getChildren().add(encodingLabel);
				}

				// 如果是GZIP压缩，添加GZIP标签
				if (executeGzip) {
					Label gzipLabel = new Label("GZIP");
					gzipLabel.setStyle(
							"-fx-background-color: #0969da; " +
									"-fx-text-fill: white; " +
									"-fx-padding: 2 6; " +
									"-fx-background-radius: 4; " +
									"-fx-font-size: 12px;"
					);
					statusBox.getChildren().add(gzipLabel);
				}

				// 设置整个状态框的样式
				statusBox.setStyle(
						"-fx-background-color: white; " +
								"-fx-border-color: #e1e4e8; " +
								"-fx-border-radius: 6; " +
								"-fx-padding: 8 12; " +
								"-fx-spacing: 15;"
				);

				// 更新响应状态标签
				responseStatusLabel.setGraphic(statusBox);
				responseStatusLabel.setStyle("-fx-padding: 0;");

				// 更新响应体
				responseBodyArea.setText(body);

				// 更新响应头表格
				responseHeadersTable.getItems().clear();
				execute.headers().forEach((name, values) -> {
					values.forEach(value -> responseHeadersTable.getItems().add(new HeaderEntry(name, value)));
				});

				// 更新响应Cookie表格
				responseCookiesTable.getItems().clear();
				if (responseCookies != null) {
					responseCookies.forEach(cookie ->
							responseCookiesTable.getItems().add(new HeaderEntry(cookie.getName(), cookie.getValue())));
				}

				// 切换到响应体标签
				responseTabPane.getSelectionModel().select(0);
			});

			// 自动保存请求到历史记录
			String currentName = nameField.getText().trim();
			if (currentName.isEmpty()) {
				currentName = String.format("%s - %s",
						methodComboBox.getValue(),
						urlField.getText().substring(0, Math.min(30, urlField.getText().length())));
			}

			// 查找是否存在相同UUID的历史记录
			RequestHistory existingHistory = historyList.stream()
					.filter(h -> h.getUuid() != null && h.getUuid().equals(currentUuid))
					.findFirst()
					.orElse(null);

			if (existingHistory != null) {
				updateExistingHistory(existingHistory);
			} else {
				RequestHistory history = new RequestHistory();
				history.setUuid(currentUuid);
				history.setName(currentName);
				history.setMethod(methodComboBox.getValue());
				history.setUrl(urlField.getText());

				// 保存Headers和Cookies
				history.setHeadersEntry(headers);
				history.setCookiesEntry(cookies);

				// 保存请求体
				history.setFormDataType(formDataRadio.isSelected());
				if (formDataRadio.isSelected()) {
					history.setFormDataEntriesEntry(formDataEntries);
				} else {
					history.setRawData(rawTextArea.getText());
					history.setRawType(rawTypeComboBox.getValue());
				}

				historyList.add(history);
			}

			updateHistoryListView();
			HistoryUtils.saveHistoryToFile(historyList);

		} catch (Exception e) {
			e.printStackTrace();
			Logs.getInstance().log("请求发送失败: " + e.getMessage());
			showAlert("错误", "请求失败: " + e.getMessage(), Alert.AlertType.ERROR);
			Platform.runLater(() -> {
				responseStatusLabel.setText("请求失败: " + e.getMessage());
				responseBodyArea.setText("错误详情:\n" + e.toString());
				responseHeadersTable.getItems().clear();
				responseCookiesTable.getItems().clear();
			});
		}
	}

	// 添加一个辅助方法来获取状态码对应的颜色
	private String getStatusColorClass(int status) {
		if (status >= 200 && status < 300) {
			return "#2ea043"; // 成功状态 - 绿色
		} else if (status >= 300 && status < 400) {
			return "#9a6700"; // 重定向状态 - 黄色
		} else if (status >= 400 && status < 500) {
			return "#cf222e"; // 客户端错误 - 红色
		} else if (status >= 500) {
			return "#a475f9"; // 服务器错误 - 紫色
		} else {
			return "#57606a"; // 其他状态 - 灰色
		}
	}

	// 添加一个方法来获取响应时间对应的颜色
	private String getDurationColorClass(long duration) {
		if (duration < 100) {
			return "#2ea043"; // 非常快 - 绿色
		} else if (duration < 500) {
			return "#0969da"; // 较快 - 蓝色
		} else if (duration < 1000) {
			return "#9a6700"; // 一般 - 黄色
		} else if (duration < 3000) {
			return "#cf222e"; // 较慢 - 红色
		} else {
			return "#a475f9"; // 很慢 - 紫色
		}
	}

	private void saveToHistory() {
		Logs.getInstance().log("开始保存到历史记录...");
		try {
			// 确保UUID不为空
			if (currentUuid == null) {
				currentUuid = java.util.UUID.randomUUID().toString();
				Logs.getInstance().log("生成新的UUID: " + currentUuid);
			}

			String currentName = nameField.getText().trim();
			if (currentName.isEmpty()) {
				currentName = "新建接口" + index++;
				nameField.setText(currentName);
			}

			// 查找是否存在相同UUID的历史记录
			RequestHistory existingHistory = historyList.stream()
					.filter(h -> h.getUuid() != null && h.getUuid().equals(currentUuid))
					.findFirst()
					.orElse(null);

			if (existingHistory != null) {
				updateExistingHistory(existingHistory);
			} else {
				RequestHistory history = new RequestHistory();
				history.setUuid(currentUuid);
				history.setName(currentName);
				history.setMethod(methodComboBox.getValue());
				history.setUrl(urlField.getText());

				// 保存Headers和Cookies
				history.setHeadersEntry(headers);
				history.setCookiesEntry(cookies);

				// 保存请求体
				history.setFormDataType(formDataRadio.isSelected());
				if (formDataRadio.isSelected()) {
					history.setFormDataEntriesEntry(formDataEntries);
				} else {
					history.setRawData(rawTextArea.getText());
					history.setRawType(rawTypeComboBox.getValue());
				}

				historyList.add(history);
			}

			updateHistoryListView();
			HistoryUtils.saveHistoryToFile(historyList);

			Logs.getInstance().log("历史记录保存成功");
			showAlert("成功", "历史记录已保存", Alert.AlertType.INFORMATION);

		} catch (Exception e) {
			e.printStackTrace();
			Logs.getInstance().log("保存历史记录失败: " + e.getMessage());
			showAlert("错误", "保存历史记录失败: " + e.getMessage(), Alert.AlertType.ERROR);
		}
	}

	private void updateExistingHistory(RequestHistory history) {
		history.setName(nameField.getText().trim());
		history.setMethod(methodComboBox.getValue());
		history.setUrl(urlField.getText());

		// 更新Headers和Cookies
		history.setHeadersEntry(headers);
		history.setCookiesEntry(cookies);

		// 更新请求体
		history.setFormDataType(formDataRadio.isSelected());
		if (formDataRadio.isSelected()) {
			history.setFormDataEntriesEntry(formDataEntries);
		} else {
			history.setRawData(rawTextArea.getText());
			history.setRawType(rawTypeComboBox.getValue());
		}
	}

	private void removeHistoryList(RequestHistory history) {
		try {
			historyList.remove(history);
			HistoryUtils.saveHistoryToFile(historyList);

			// 如果删除的是当前正在编辑的记录，重置表单
			if (history.getUuid() != null && history.getUuid().equals(currentUuid)) {
				resetForm();
			}

			Logs.getInstance().log("历史记录删除成功");
			showAlert("成功", "历史记录已删除", Alert.AlertType.INFORMATION);

		} catch (Exception e) {
			e.printStackTrace();
			Logs.getInstance().log("删除历史记录失败: " + e.getMessage());
			showAlert("错误", "删除历史记录失败: " + e.getMessage(), Alert.AlertType.ERROR);
		}
	}

	private void updateHistoryListView() {
		// 保存当前选中的项
		RequestHistory selectedItem = historyListView.getSelectionModel().getSelectedItem();

		// 更新列表
		historyListView.setItems(FXCollections.observableArrayList(historyList));

		// 恢复选中状态
		if (selectedItem != null) {
			for (RequestHistory h : historyListView.getItems()) {
				if (h.getName().equals(selectedItem.getName())) {
					historyListView.getSelectionModel().select(h);
					historyListView.scrollTo(h);
					break;
				}
			}
		}

		historyListView.setCellFactory(lv -> new ListCell<RequestHistory>() {
			private final Button deleteButton = new Button("删除");
			private final Label label = new Label();
			private final HBox container = new HBox();

			{
				// 设置容器样式
				container.setAlignment(Pos.CENTER_LEFT);
				container.setSpacing(10);

				// 让标签占据所有剩余空间
				HBox.setHgrow(label, Priority.ALWAYS);

				// 设置删除按钮样式
				deleteButton.getStyleClass().addAll("button", "danger-button"); // 添加基础button类

				// 创建右侧容器用于放置删除按钮
				HBox rightContainer = new HBox(deleteButton);
				rightContainer.setAlignment(Pos.CENTER_RIGHT);
				rightContainer.setPadding(new Insets(0, 5, 0, 0));

				// 将标签和右侧容器添加到主容器
				container.getChildren().addAll(label, rightContainer);

				// 添加双击事件
				setOnMouseClicked(event -> {
					if (event.getClickCount() == 2 && getItem() != null) {
						loadHistoryItem(getItem());
					}
				});

				deleteButton.setOnAction(event -> {
					RequestHistory item = getItem();
					if (item != null) {
						historyList.remove(item);
						removeHistoryList(item);
						updateHistoryListView();
					}
				});
			}

			@Override
			protected void updateItem(RequestHistory item, boolean empty) {
				super.updateItem(item, empty);
				if (empty || item == null) {
					setText(null);
					setGraphic(null);
				} else {
					label.setText(String.format("%s - %s", item.getMethod(), item.getName()));
					// 设置单元格内容的对齐方式
					setAlignment(Pos.CENTER_LEFT);
					setGraphic(container);
				}
			}
		});

		historyListView.refresh();
	}

	private void loadHistoryItem(RequestHistory history) {
		try {
			// 设置基本信息
			currentUuid = history.getUuid();
			nameField.setText(history.getName());
			methodComboBox.setValue(history.getMethod());
			urlField.setText(history.getUrl());

			// 清空现有的请求头和Cookies
			headers.clear();
			cookies.clear();
			headersContainer.getChildren().clear();
			cookiesContainer.getChildren().clear();

			// 重新创建输入行
			headerNameField = new TextField();
			headerValueField = new TextField();
			cookieNameField = new TextField();
			cookieValueField = new TextField();

			// HBox headerInputRow = createInputRow(headerNameField, headerValueField, new Button("添加"), this::addHeader);
			// HBox cookieInputRow = createInputRow(cookieNameField, cookieValueField, new Button("添加"), this::addCookie);

			// headersContainer.getChildren().add(headerInputRow);
			// cookiesContainer.getChildren().add(cookieInputRow);

			// 加载请求头
			if (history.getHeaders() != null) {
				for (HeaderVo headerVo : history.getHeaders()) {
					if (headerVo.getName() != null && !headerVo.getName().trim().isEmpty()) {
						HeaderEntry header = new HeaderEntry(headerVo.getName(), headerVo.getValue());
						headers.add(header);
						HBox row = createHeaderRow(header, headers, headersContainer);
						headersContainer.getChildren().add(row);
					}
				}
			}

			// 加载Cookies
			if (history.getCookies() != null) {
				for (HeaderVo cookie : history.getCookies()) {
					if (cookie.getName() != null && !cookie.getName().trim().isEmpty()) {
						HeaderEntry cookieEntry = new HeaderEntry(cookie.getName(), cookie.getValue());
						cookies.add(cookieEntry);
						HBox row = createHeaderRow(cookieEntry, cookies, cookiesContainer);
						cookiesContainer.getChildren().add(row);
					}
				}
			}

			// 加载Form-Data
			if (history.getFormDataType()) {
				formDataEntries.clear();
				formDataEntriesContainer.getChildren().clear();

				if (history.getFormDataEntries() != null) {
					for (BodyVo entry : history.getFormDataEntries()) {
						if (entry.getName() != null && !entry.getName().trim().isEmpty()) {
							BodyEntry newEntry = new BodyEntry();
							newEntry.setName(entry.getName());
							newEntry.setType(entry.getType());

							if ("文件".equals(entry.getType()) && entry.getFullPath() != null) {
								if (FileUtil.exist(entry.getFullPath())) {
									newEntry.setValue(new File(entry.getFullPath()));
								}
							} else {
								newEntry.setValue(entry.getValue());
							}

							newEntry.setFullPath(entry.getFullPath());
							formDataEntries.add(newEntry);

							HBox row = createFormDataRow(newEntry, formDataEntries, formDataEntriesContainer);
							formDataEntriesContainer.getChildren().add(row);
						}
					}
				}
			}

			// 添加空白行到最后
			addEmptyHeaderRow();
			addEmptyCookieRow();
			if (history.getFormDataType()) {
				addEmptyFormDataRow();
			}

		} catch (Exception e) {
			e.printStackTrace();
			Logs.getInstance().log("加载历史记录失败: " + e.getMessage());
			showAlert("错误", "加载历史记录失败: " + e.getMessage(), Alert.AlertType.ERROR);
		}
	}

	private void addEmptyFormDataRow() {
		formDataNameField = new TextField();
		formDataValueField = new TextField();
		formDataTypeComboBox = new ComboBox<>();
		HBox formDataInputRow = createFormDataInputRow(formDataNameField, formDataValueField, formDataTypeComboBox, this::addFormData);
		formDataEntriesContainer.getChildren().add(formDataInputRow);
	}

	private void resetForm() {
		// 重置基本字段
		nameField.clear();
		urlField.clear();
		methodComboBox.setValue("GET");

		// 清空请求头和Cookie
		headers.clear();
		cookies.clear();
		headersContainer.getChildren().clear();
		cookiesContainer.getChildren().clear();
		formDataEntries.clear();
		formDataEntriesContainer.getChildren().clear();

		// 添加初始空白行
		headerNameField = new TextField();
		headerValueField = new TextField();
		cookieNameField = new TextField();
		cookieValueField = new TextField();
		formDataNameField = new TextField();
		formDataValueField = new TextField();
		formDataTypeComboBox = new ComboBox<>();

		HBox headerInputRow = createInputRow(headerNameField, headerValueField, new Button("添加"), this::addHeader);
		HBox cookieInputRow = createInputRow(cookieNameField, cookieValueField, new Button("添加"), this::addCookie);
		HBox formDataInputRow = createFormDataInputRow(formDataNameField, formDataValueField, formDataTypeComboBox, this::addFormData);

		headersContainer.getChildren().add(headerInputRow);
		cookiesContainer.getChildren().add(cookieInputRow);
		formDataEntriesContainer.getChildren().add(formDataInputRow);

		// 重置请求体
		formDataRadio.setSelected(true);
		rawTextArea.clear();
		rawTypeComboBox.setValue("JSON");

		// 清空响应
		responseBodyArea.clear();
		responseHeadersTable.getItems().clear();
		responseCookiesTable.getItems().clear();
		responseStatusLabel.setText("");

		// 生成新的UUID
		currentUuid = java.util.UUID.randomUUID().toString();
	}

	@FXML
	private void addHeader() {
		String name = headerNameField.getText().trim();
		String value = headerValueField.getText().trim();

		if (!name.isEmpty()) {
			HeaderEntry header = new HeaderEntry(name, value);
			headers.add(header);

			// 创建新的行并插入到输入行之前
			HBox row = createHeaderRow(header, headers, headersContainer);
			headersContainer.getChildren().add(headersContainer.getChildren().size() - 1, row);

			// 清空输入框
			headerNameField.clear();
			headerValueField.clear();
		}
	}

	@FXML
	private void addCookie() {
		String name = cookieNameField.getText().trim();
		String value = cookieValueField.getText().trim();

		if (!name.isEmpty()) {
			HeaderEntry cookie = new HeaderEntry(name, value);
			cookies.add(cookie);

			// 创建新的行并插入到输入行之前
			HBox row = createHeaderRow(cookie, cookies, cookiesContainer);
			cookiesContainer.getChildren().add(cookiesContainer.getChildren().size() - 1, row);

			// 清空输入框
			cookieNameField.clear();
			cookieValueField.clear();
		}
	}

	private HBox createHeaderRow(HeaderEntry entry, List<HeaderEntry> list, VBox container) {
		HBox row = new HBox(5);
		row.setAlignment(Pos.CENTER_LEFT);
		row.setPadding(new Insets(2));
		row.setStyle("-fx-background-color: #f6f8fa; -fx-background-radius: 6;");

		TextField nameField = new TextField(entry.getName());
		nameField.setPrefWidth(200);
		nameField.setPrefHeight(30);
		nameField.textProperty().bindBidirectional(entry.nameProperty());
		nameField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		TextField valueField = new TextField(entry.getValue());
		valueField.setPrefHeight(30);
		HBox.setHgrow(valueField, Priority.ALWAYS);
		valueField.textProperty().bindBidirectional(entry.valueProperty());
		valueField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

		Button deleteButton = new Button("删除");
		deleteButton.getStyleClass().add("danger-button");
		deleteButton.setOnAction(e -> {
			list.remove(entry);
			container.getChildren().remove(row);
		});

		row.getChildren().addAll(nameField, valueField, deleteButton);
		return row;
	}

	private void initResponseHeadersTable() {
		TableColumn<HeaderEntry, String> nameCol = (TableColumn<HeaderEntry, String>) responseHeadersTable.getColumns().get(0);
		TableColumn<HeaderEntry, String> valueCol = (TableColumn<HeaderEntry, String>) responseHeadersTable.getColumns().get(1);

		// 设置列的值工厂
		nameCol.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
		valueCol.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
	}

	private void initResponseCookiesTable() {
		TableColumn<HeaderEntry, String> nameCol = (TableColumn<HeaderEntry, String>) responseCookiesTable.getColumns().get(0);
		TableColumn<HeaderEntry, String> valueCol = (TableColumn<HeaderEntry, String>) responseCookiesTable.getColumns().get(1);

		// 设置列的值工厂
		nameCol.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
		valueCol.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
	}

	private Button createButton(String text, String... styleClasses) {
		Button button = new Button(text);
		button.getStyleClass().add("button");
		button.getStyleClass().addAll(styleClasses);
		return button;
	}

}
